package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.restapi.Bmob;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.User;
import okhttp3.RequestBody;
import okhttp3.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2022-04-10
 */
@Controller
@RequestMapping("/system/teacher")
public class UserController extends BaseController {

    private String prefix = "system/teacher";

    private String appId = "7e07be332a9fc1138036ed1e73d88d47";
    private String key = "c466a05bb058480cfc06c252b774ce8c";
    private String secret = "24e092ed107198f0";
    private String master = "d332da0c53272f48aea70ccc8e2bb8a4";
    private String table = "_User";

    @RequiresPermissions("system:teacher:view")
    @GetMapping()
    public String user() {
        return prefix + "/teacher";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:teacher:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(User user) {

        init();
        String res = Bmob.findAll(table);
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("results").toString());
        System.out.println(jsonArray);
        List<User> list = JSONObject.parseArray(jsonArray.toString(), User.class);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:teacher:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(User user) {
        init();
        String res = Bmob.findAll(table);
        JSONObject jsonObject = JSONObject.parseObject(res);
        JSONArray jsonArray = JSONArray.parseArray(jsonObject.get("results").toString());
        System.out.println(jsonArray);
        List<User> list = JSONObject.parseArray(jsonArray.toString(), User.class);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    private void init() {
        Bmob.initBmob(appId, key);
        Bmob.initMaster(master);
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("system:teacher:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(User user) {
        init();
        String userPam = JSONObject.toJSONString(user);
        String i = Bmob.insert(table, userPam);
        System.out.println(i);
        return toAjax(1);
    }

    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("system:teacher:edit")
    @GetMapping("/edit/{objectId}")
    public String edit(@PathVariable("objectId") String objectId, ModelMap mmap) {
        init();
        String i = Bmob.findOne(table, objectId);
        System.out.println(i);
        User user = JSONObject.parseObject(i, User.class);
        mmap.put("user", user);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("system:teacher:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(User user) throws IOException {
        init();
        String mURL = "https://api2.bmob.cn/1/classes/" + table + "/" + user.getObjectId();
        OkHttpClient client = new OkHttpClient().newBuilder() //
                .readTimeout(60, TimeUnit.SECONDS) // 设置读取超时时间
                .writeTimeout(60, TimeUnit.SECONDS) // 设置写的超时时间
                .connectTimeout(60, TimeUnit.SECONDS) // 设置连接超时时间
                .build();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        Map map = new HashMap();
        map.put("email", user.getEmail());
        map.put("mobilePhoneNumber", user.getMobilePhoneNumber());
        map.put("nick", user.getNick());
        map.put("password", user.getPassword());
        map.put("userName", user.getUsername());
        RequestBody body = RequestBody.create(JSON, JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(mURL).put(body)
                .addHeader("X-Bmob-Application-Id", appId)
                .addHeader("X-Bmob-Application-Id", appId)
                .addHeader("X-Bmob-Master-Key", master).build();
        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
        return toAjax(1);
    }


    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:teacher:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) throws IOException {
        init();
//        String id = Bmob.delete(table, ids);
        OkHttpClient client = new OkHttpClient().newBuilder() //
                .readTimeout(60, TimeUnit.SECONDS) // 设置读取超时时间
                .writeTimeout(60, TimeUnit.SECONDS) // 设置写的超时时间
                .connectTimeout(60, TimeUnit.SECONDS) // 设置连接超时时间
                .build();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        Map map = new ModelMap();
        map.put("objectId", ids);
        String mURL = "https://api2.bmob.cn/1/classes/" + table + "/" + ids;
        RequestBody body = RequestBody.create(JSON, JSONObject.toJSONString(map));
        Request request = new Request.Builder().url(mURL).delete(body)
                .addHeader("X-Bmob-Application-Id", appId)
                .addHeader("X-Bmob-Application-Id", appId)
                .addHeader("X-Bmob-Master-Key", master).build();
        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
        return toAjax(1);

    }


}
